package com.zyy.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Description: 类描述
 * @Author: zyy
 * @Date: 2022/10/17 17:46
 */
@Controller
public class LoginController {

    @RequestMapping({"/", "/index"})
    public String toIndex(Model model) {
        model.addAttribute("msg", "hello shiro");
        return "index";
    }


    @RequestMapping("/user/add")
    public String add() {
        return "user/add";
    }

    @RequestMapping("/user/update")
    public String update() {
        return "user/update";
    }

    @RequestMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    @RequestMapping("/login")
    public String login(String username, String password, Model model) {
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //生成token
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            //登录
            subject.login(token);
            Session session = subject.getSession();
            session.setAttribute("loginUser",username);
            //跳转首页
            return "index";
        } catch (UnknownAccountException e) {
            model.addAttribute("msg", "用户名不存在");
        } catch (IncorrectCredentialsException e) {
            model.addAttribute("msg", "密码有误");
        } catch (AuthenticationException e) {
            model.addAttribute("msg", "认证失败");
        }
        //异常还是跳转到登录页面
        return "login";
    }

    @RequestMapping("/noAuth")
    @ResponseBody
    public String noAuth() {
        return "未经授权，无法访问";
    }
}
